package com.example.wblog.controller;

import com.example.wblog.model.Article;
import com.example.wblog.model.LoginTicket;
import com.example.wblog.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Controller
public class BlogController {

    @Autowired
    ArticleService articleService;

    //page
    @RequestMapping({"/", "/index"})
    public String index() {
        return "redirect:/page/1";
    }

    @RequestMapping({"/page/{pageId}"})
    public String page(Model model,
                       @PathVariable("pageId") int pageId) {
        final int SIZE = 5;
        int offset = (pageId - 1) * SIZE;
        List<Article> articleList = articleService.selectList(offset, SIZE);
        model.addAttribute("article_list", articleList);
        return "index";
    }

    //category
    @RequestMapping({"/categories"})
    public String categories() {
        return "categories";
    }

    @RequestMapping({"/category/{categoryName}"})
    public String categoryIndex(@PathVariable("categoryName") String categoryName) {
        return category(categoryName, 1);
    }


    @RequestMapping({"/category/{categoryName}/{pageId}"})
    public String category(@PathVariable("categoryName") String categoryName,
                           @PathVariable("pageId") int pageId) {
        return "category" + categoryName + pageId;
    }

    //tag
    @RequestMapping({"/tags"})
    public String tags() {
        return "tag";
    }

    @RequestMapping({"/tag/{tagName}"})
    public String tagIndex(@PathVariable("tagName") String tagName) {
        return tag(tagName, 1);
    }

    @RequestMapping({"/tag/{tagName}/{pageId}"})
    public String tag(@PathVariable("tagName") String tagName,
                           @PathVariable("pageId") int pageId) {
        return "tag" + tagName + pageId;
    }

    //detail
    @RequestMapping({"/article/{articleId}"})
    public String detail(Model model,
                         @PathVariable("articleId") int articleId) {
        Article article = articleService.selectById(articleId);
        if(article != null) {
            model.addAttribute("article", article);
        }
        return "detail";
    }
}
